package com.marcowu.study.spb.tracing.client;

import com.marcowu.study.spb.tracing.zipkin.RequestBuilderCarrier;
import com.marcowu.study.spb.tracing.zipkin.TraceUtil;
import io.opentracing.Tracer;
import io.opentracing.propagation.Format;
import io.opentracing.tag.Tags;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MyClient {

  @Autowired
  private OkHttpClient httpClient;

  private Tracer tracer = TraceUtil.getZipkinTracer("client");

  public String httpGet(String path) {
    try {
      HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost").port(9000).addPathSegments(path).build();
      Request.Builder requestBuilder = new Request.Builder().url(url);

      Tags.SPAN_KIND.set(tracer.activeSpan(), Tags.SPAN_KIND_CLIENT);
      Tags.HTTP_METHOD.set(tracer.activeSpan(), "GET");
      Tags.HTTP_URL.set(tracer.activeSpan(), url.toString());
      tracer.inject(tracer.activeSpan().context(), Format.Builtin.HTTP_HEADERS, new RequestBuilderCarrier(requestBuilder));

      Request request = requestBuilder.build();
      Response response = httpClient.newCall(request).execute();
      if (response.code() >= 400) {
        throw new RuntimeException("Bad HTTP result: " + response);
      }
      return response.body().string();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}
